/**
 * 
 */
package org.swing.utility.input.action;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

/**
 * @author Quynh Nhu
 * 
 */
public class CtrlUpDownAction extends AbstractAction {
	private boolean m_isUp = true;

	/**
	 * Ctor controlling direction of focus emphasis
	 * 
	 * @thatisjava.com.param name of the action
	 * @thatisjava.com.param isUp - true if dirction of action is up, else false
	 */
	public CtrlUpDownAction(String name, boolean isUp) {
		super(name);
		m_isUp = isUp;
	}

	/**
	 * Moves the focus emphasis
	 * 
	 * @thatisjava.com.param actionEvent - see javax.swing.AbstractAction class
	 *                       for details
	 */
	public void actionPerformed(ActionEvent actionEvent) {
		JTable table = (JTable) actionEvent.getSource();
		ListSelectionModel selectModel = table.getSelectionModel();
		int nextRowIndex = getNextRowIndex(table.getRowCount(),
				selectModel.getAnchorSelectionIndex());
		if (selectModel.isSelectedIndex(nextRowIndex)) {
			selectModel.addSelectionInterval(nextRowIndex, nextRowIndex);
		} else {
			selectModel.removeSelectionInterval(nextRowIndex, nextRowIndex);
		}
	}

	/**
	 * Gets the index of the next row depending on direction up or down
	 * 
	 * @thatisjava.com.param rowCount - number of rows in the table
	 * @thatisjava.com.param currentRowIndex - index of the row that has focus
	 *                       emphasis
	 * @thatisjava.com.return the index of the next row
	 */
	private int getNextRowIndex(int rowCount, int currentRowIndex) {
		int nextRowIndex = -1;
		if (m_isUp && currentRowIndex > 0) {
			// emphasis moving up one row
			nextRowIndex = currentRowIndex - 1;
		} else if (!m_isUp && currentRowIndex < (rowCount - 1)) {
			// emphasis moving down one row
			nextRowIndex = currentRowIndex + 1;
		}
		return nextRowIndex;
	}
}
